﻿using Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFake;
using NB.MGJ.Service.AntiFake;
using NB.MGJ.Service.FWSearch;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace NB.MGJ.Web.Controllers
{
    public class CodeSearchController : Controller
    {
        AntiFakeVerifyService _AntiFakeVerifyService;
        AntiFakeQueryCodeLogService _AntiFakeQueryCodeLogService;

        AntiFake_PageCreateService _AntiFake_PageCreateService;
        public QueryStatisticsService _qsService;

        public AntiFakeButtonService _AntiFakeButtonService;
        public FWSearchService fw;
        public CodeSearchController()
        {

            _AntiFakeVerifyService = new AntiFakeVerifyService();
            _AntiFakeQueryCodeLogService = new AntiFakeQueryCodeLogService();
            _AntiFake_PageCreateService = new AntiFake_PageCreateService();
            _qsService = new QueryStatisticsService();
            _AntiFakeButtonService = new AntiFakeButtonService();
            fw = new FWSearchService();
        }


        public ActionResult OriginsSearch(string code = "20140595260158004245")
        {
            var dt = new DataTable(); ;
            string type = _AntiFake_PageCreateService.CheckCodeType(code);

            dt = _AntiFakeVerifyService.GetCodeModel(code, type);

            var productId = dt.Rows[0]["ProductId"];
            var productBatchId = dt.Rows[0]["ProductBatchId"];
            var errorMsg = "";
            if (Convert.ToInt32(productBatchId) == 0)
            {
                errorMsg = "该码尚未绑定批次！";
                return RedirectToAction("OriginsErrorPage", "MaterialPreview", new
                {
                    errorMsg = errorMsg
                });
            }

            if (Convert.ToInt32(productId) == 0)
            {
                errorMsg = "该码尚未绑定产品！";
                return RedirectToAction("OriginsErrorPage", "MaterialPreview", new
                {
                    errorMsg = errorMsg
                });
            }


            //var dtCode = new DataTable();
            //dtCode = _AntiFakeVerifyService.GetCodeModel(code, type);
            string Fw_CodeSecret = Convert.ToString(dt.Rows[0]["Fw_CodeSecret"]);


            return RedirectToAction("ViewCenterSearch", "MaterialPreview", new
            {
                productId = productId,
                productBatchId = productBatchId,
                Fw_CodeSecret = Fw_CodeSecret
            });


        }



        //防伪查询页面
        public ActionResult AntifakeSearch(string code = "0669002002319196")
        {
            string type = _AntiFake_PageCreateService.CheckCodeType(code);
            var dt = new DataTable();
            dt = _AntiFakeVerifyService.GetCodeModel(code, type);

            var codeStatus = dt.Rows[0]["Stats"];

            string Fw_CodeSecret = Convert.ToString(dt.Rows[0]["Fw_CodeSecret"]);

            if (type == "Wl_Code")
            {
                type = "Fw_Code";
            }
            MarketController market = new MarketController();
            Hashtable ht = market.IsMarketing(Fw_CodeSecret);
            int IsActivity = int.Parse(ht["b"].ToString());
            //int EID = _AntiFake_PageCreateService.GetEIDByCode(code);
            int EID = Convert.ToInt32(dt.Rows[0]["EnterpriseId"]);

            var pageModel = _AntiFake_PageCreateService.GetEnterpriseDefaultAntiFakePage(EID);
            if (pageModel == null)
            {
                pageModel = _AntiFake_PageCreateService.CreatePageModel(EID, 1);
            }
            ViewBag.pageModel = pageModel;
            ViewBag.type = type;
            ViewBag.code = code;
            ViewBag.Fw_CodeSecret = Fw_CodeSecret;

            ViewBag.codeStatus = codeStatus;
            ViewBag.IsActivity = IsActivity;
            ViewBag.ActivityModel = ht["model"];
            return View();
        }


        public ActionResult ValidateCodeLastFour(string code, string verCode)
        {
            var dt = new DataTable();
            string type = _AntiFake_PageCreateService.CheckCodeType(code);
            dt = _AntiFakeVerifyService.GetCodeModel(code, type);
            string Fw_CodeSecret = Convert.ToString(dt.Rows[0]["Fw_CodeSecret"]);


            var verCodeInDB = "";
            //var verCodeInDB = Fw_CodeSecret.Substring(Fw_CodeSecret.Length - 4, Fw_CodeSecret.Length);
            try
            {
                verCodeInDB = Fw_CodeSecret.Substring(Fw_CodeSecret.Length - 4, 4);
            }
            catch (Exception ex)
            {
                throw ex;
            }


            if (verCode == verCodeInDB)
            {
                return Json(true);
            }
            else
            {
                return Json(false);
            }

        }




        //防伪查询结果页面
        public ActionResult AntifakeSearchResult(string code = "20140595260158004245", string searchType = "Fw_Code", string verCode = "")
        {


            string Fw_CodeSecret = string.Empty;
            var dt = new DataTable();
            string type = _AntiFake_PageCreateService.CheckCodeType(code);
            dt = _AntiFakeVerifyService.GetCodeModel(code, type);
            if (dt != null)
            {
                Fw_CodeSecret = Convert.ToString(dt.Rows[0]["Fw_CodeSecret"]);
            }



            if (searchType == "Fw_Code")
            {
                return RedirectToAction("OriginsSearch", new
                {
                    code = code
                });
            }

            ViewBag.type = "Fw_CodeSecret";
            ViewBag.code = Fw_CodeSecret;

            return View();
        }




        #region  防伪查询页面接口（Button）

        public ActionResult GetButtonList(int moduleId)
        {
            List<antifake_button> list = new List<antifake_button>();

            list = _AntiFakeButtonService.GetListByModuleId(moduleId);
            if (list.Count == 0)
            {
                list = _AntiFakeButtonService.CreateButtonListTemplet(2);
            }
            return Json(list);
        }




        #endregion

        #region  获取用户IP
        protected string UserIp
        {
            get
            {

                string userIP = string.Empty;

                try
                {
                    if (System.Web.HttpContext.Current == null
                     || System.Web.HttpContext.Current.Request == null
                     || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    {
                        return "";
                    }

                    string CustomerIP = "";

                    CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                    if (!string.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                    if (!String.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                        if (CustomerIP == null)
                        {
                            CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                        }
                    }
                    else
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }

                    if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
                    {
                        return System.Web.HttpContext.Current.Request.UserHostAddress;
                    }
                    return CustomerIP;
                }
                catch
                {
                }

                return userIP;
            }
        }





        public string Serialize(DataTable dt)
        {
            if (dt == null)
            {
                return "-1";
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return serializer.Serialize(list);
        }



        public LogOnUserModel LogOnUser
        {
            get
            {
                return SessionHelper.LogOnUser<LogOnUserModel>();
            }
        }


        #endregion

        #region   防伪调用函数

        public string SearchCreatCode(string Code, string type)
        {
           
            var Codes = "";
            string sqlWhere = "";
            var reply = "";
            var Scodes = MiMa.Jiemi(Code, AppConst.DigitCodeKey);
            var stats = _AntiFakeVerifyService.states(Code);
            if (stats == 2)
            {
                return JsonConvert.SerializeObject(new
                {
                    results = "2"

                });
            }
            var getsearchecode = Scodes.Substring(0, AppConst.SubStrLen);
            var GetEnterId = _AntiFakeVerifyService.GetEnterId(getsearchecode, Code);
             if (getsearchecode == null || GetEnterId == null)
            {
                return JsonConvert.SerializeObject(new
                {
                    results = "-1",
                    res = ""
                });
            }//如果输入错误码
            
            if (GetEnterId.Length == 5 || GetEnterId.Length == 1)
            {
                GetEnterId = "000" + GetEnterId;
            }
            else if (GetEnterId.Length == 6 || GetEnterId.Length == 2)
            {
                GetEnterId = "00" + GetEnterId;
            }
            else if (GetEnterId.Length == 7 || GetEnterId.Length == 3)
            {
                GetEnterId = "0" + GetEnterId;
            }

            //var stats = _AntiFakeVerifyService.state(Code);

            int EnterCode = int.Parse(getsearchecode);
            int err = _AntiFakeVerifyService.GetCodes(Code);
            if (err == 0)
            {
                reply = _AntiFakeVerifyService.ReplyInfoService(EnterCode);
            }
            else
            {
                if (!string.IsNullOrEmpty(Code))
                {

                    if (!string.IsNullOrEmpty(Code))
                    {
                        sqlWhere = string.Format(@" AND {0}='{1}'", type, Code);
                    }

                }

            }
            if (type == "Fw_CodeSecret")
            {
                Codes = MiMa.Jiemi(Code, AppConst.DigitCodeKey);
            }
            var eCode = Codes.Substring(0, 4);
            string fCode = Codes.Substring(0, AppConst.SubStrLen);
            string bcode = fCode.Substring(4, AppConst.SubBatchLen);
            var result = _AntiFakeVerifyService.GetCodeService(eCode, fCode, Codes, bcode, sqlWhere);


            var rs = new CodeLog
            {
                Fw_SCode = result != null ? Scodes : Codes,
                Fw_Code = result != null ? Code : null,
                QueryType = 0,
                QueryTime = DateTime.Now,
                QueryIp = UserIp,


                Valid = result == null || result.Rows.Count == 0 ? 0 : 1,
                ProductId = result != null && !(result.Rows[0]["ProductId"] is DBNull) ? Convert.ToInt32(result.Rows[0]["ProductId"]) : 0,
                EnterpriseId = result != null && !(result.Rows[0]["EnterpriseId"] is DBNull) ? Convert.ToInt32(result.Rows[0]["EnterpriseId"]) : 0
            };


            FWSearchService.UpdateAntifakeLog_Provice_City(rs);
            _AntiFakeVerifyService.AddCodeSearchLog(rs, GetEnterId, Code);
            var firsttimes = _AntiFakeVerifyService.FirstSearch(Code, GetEnterId);

            return JsonConvert.SerializeObject(new
            {
                results = Serialize(result),
                res = reply,
                num = _AntiFakeVerifyService.searchtimes(Code, GetEnterId),
                firsttime = firsttimes,
                QueryIp = UserIp
            });
        }
        public string GetCodeLogDis(string Code)
        {


            string strCode = MiMa.Jiemi(Code.Trim(), AppConst.DigitCodeKey);
            string ecode = strCode.Substring(0, AppConst.SubStrLen);
            var GetEnterId = _AntiFakeVerifyService.GetEnterId(ecode, Code);
            if (GetEnterId.Length == 5 || GetEnterId.Length == 1)
            {
                GetEnterId = "000" + GetEnterId;
            }
            else if (GetEnterId.Length == 6 || GetEnterId.Length == 2)
            {
                GetEnterId = "00" + GetEnterId;
            }
            else if (GetEnterId.Length == 7 || GetEnterId.Length == 3)
            {
                GetEnterId = "0" + GetEnterId;
            }

            return JsonConvert.SerializeObject(new
            {
                info = Serialize(_AntiFakeVerifyService.GetCodeLogDis(Code, GetEnterId)),
                num = _AntiFakeVerifyService.searchtimes(Code, GetEnterId),
                QueryIp = UserIp
            });

        }




        #endregion






    }
}